package web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import db.ActivityApplicationRepository;
import db.ActivityRepository;
import db.AnnouncementRepository;
import db.ClubAdministratorRepository;
import db.ClubRepository;
import db.MembershipApplicationRepository;
import db.UserRepository;
import domain.Activity;
import domain.ActivityApplication;
import domain.Announcement;
import domain.Club;
import domain.ClubAdministrator;
import domain.MembershipApplication;
import domain.User;

import javax.servlet.http.HttpSession;

import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 管理员控制类
 *
 * @author zdc
 */
@Controller
@SessionAttributes({ "clubAdministrator" })
@RequestMapping("/clubAdministrator")

public class ClubAdministratorController {

    private static final RequestMethod[] PUT = null;
    @Autowired
    private ClubAdministratorRepository clubAdministratorRepository;
    @Autowired
    private ClubRepository clubRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ActivityRepository activityRepository;
    @Autowired
    private AnnouncementRepository announcementRepository;
    @Autowired
    private MembershipApplicationRepository membershipApplicationRepository;
    @Autowired
    private ActivityApplicationRepository activityApplicationRepository;

    /**
     * 社团管理员首页
     *
     * @param session 会话对象，用于获取当前管理员信息
     * @param model model对象
     * @return 首页视图
     */
    @RequestMapping(value = "/index", method = GET)
    public String showIndex(HttpSession session, Model model) {
        Date now = new Date();
        model.addAttribute("now", now);
        Club club = (Club) session.getAttribute("club");
        int ClubID = club.getClubID();
        long memberCount = userRepository.countByClubID(ClubID);
        long clubAdministratorCount = clubAdministratorRepository.countByClubID(ClubID);
        long activityCount = activityRepository.countByClubID(ClubID);
        long announceCount = announcementRepository.countByClubID(ClubID);

        model.addAttribute("memberCount", memberCount);
        model.addAttribute("clubAdministratorCount", clubAdministratorCount);
        model.addAttribute("activityCount", activityCount);
        model.addAttribute("announceCount", announceCount);

        return "/clubAdministrator/index";
    }

    /**
     * 社团管理员信息页面
     *
     * @param session 会话对象，用于获取当前管理员信息
     * @param model model对象
     * @return 社团管理员个人信息视图
     */
    @RequestMapping(value = "/accountInfo", method = GET)
    public String showAccountInfo(HttpSession session, Model model) {
        ClubAdministrator clubAdministrator = (ClubAdministrator) session.getAttribute("clubAdministrator");
        model.addAttribute("clubAdministrator", clubAdministrator);
        return "/clubAdministrator/accountInfo";
    }

    /**
     * 更新社团管理员个人信息
     *
     * @param password 密码
     * @param email 邮箱
     * @param nickname 昵称
     * @param telephone 电话
     * @param gender 性别
     * @param college 学院
     * @param session 会话对象,用于获取当前管理员信息
     * @param model 模型数据
     * @return 社团管理员个人信息视图
     */
    @RequestMapping(value = "/accountInfo", method = POST)
    public String update(@RequestParam(value = "password") String password,
                         @RequestParam(value = "email") String email,
                         @RequestParam(value = "nickname") String nickname,
                         @RequestParam(value = "telephone") String telephone,
                         @RequestParam(value = "gender") String gender,
                         @RequestParam(value = "college") String college,
                         @RequestParam(value = "studentID") String studentID,
                         HttpSession session, Model model) {
        try {
            if (password.isEmpty()||nickname.isEmpty()||college.isEmpty()||studentID.isEmpty()){
                throw new Exception();
            }
            ClubAdministrator clubAdministrator = (ClubAdministrator) session.getAttribute("clubAdministrator");
            clubAdministrator.setPassword(password);
            clubAdministrator.setEmail(email);
            clubAdministrator.setNickname(nickname);
            clubAdministrator.setTelephone(telephone);
            clubAdministrator.setGender(Objects.equals(gender, "true"));
            clubAdministrator.setCollege(college);
            clubAdministrator.setStudentID(studentID);
            boolean isUpdated = clubAdministratorRepository.updateClubAdministrator(clubAdministrator);
            session.setAttribute("deleted", isUpdated);
        } catch (Exception e) {
            session.setAttribute("deleted", false);
        }
        return "/clubAdministrator/accountInfo";
    }


    /**
     * 显示社团成员列表
     *
     * @param keyword 搜索的关键词
     * @param page    当前页面号
     * @param session 会话对象，用于获取当前社团信息
     * @param model   Model对象
     * @return 成员列表页面
     */
    @RequestMapping(value = "/users", method = GET)
    public String viewUsers(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "page", defaultValue = "1") int page, HttpSession session, Model model) {
        Club club = (Club) session.getAttribute("club");
        int clubID = club.getClubID();
        List<User> allusers = clubRepository.listMembers(clubID);
        List<User> userList;
        if (keyword == null || keyword.isEmpty()) {
            userList = allusers;
        } else {
            userList = allusers.stream()
                    .filter(user -> user.getUsername() != null && user.getUsername().contains(keyword))
                    .collect(Collectors.toList());
        }
        model.addAttribute("userList", userList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (userList.size() + 9) / 10);
        return "/clubAdministrator/users";
    }



	/**
	 * 创建一个新的活动
	 * 
	 * @param model model对象
	 * @return 活动申请页面
	 */
	@RequestMapping(value = "/activityApplication", method = GET)
	public String showAddActivity(Model model) {

		model.addAttribute("now", new Date());
		return "/clubAdministrator/activityApplication";
	}

	/**
     * 填表创建活动申请
	 *
     * @param activityName 活动名称
     * @param startYear 开始年份
     * @param startMonth 开始月份
     * @param startDay 开始日期
     * @param startHour 开始小时
     * @param startMin 开始分钟
     * @param endYear 结束年份
     * @param endMonth 结束月份
     * @param endDay 结束日期
     * @param endHour 结束小时
     * @param endMin 结束分钟
     * @param place 活动地点
     * @param description 活动描述
     * @param session 会话对象
     * @return 活动申请页面
	 */
	@RequestMapping(value = "/activityApplication", method = POST)
    public String processAddActivity(
            @RequestParam("activityName") String activityName,
            @RequestParam("startYear") int startYear,@RequestParam("startMonth") int startMonth,
            @RequestParam("startDay") int startDay,@RequestParam("startHour") int startHour,
            @RequestParam("startMin") int startMin,
            @RequestParam("endYear") int endYear,@RequestParam("endMonth") int endMonth,
            @RequestParam("endDay") int endDay,@RequestParam("endHour") int endHour,
            @RequestParam("endMin") int endMin,
            @RequestParam("place") String place,
            @RequestParam("description") String description,
            HttpSession session) {

        try {
            int s = new Date().getSeconds();
            Date startTime = new Date(startYear-1900,startMonth-1,startDay,startHour,startMin,s);
            Date endTime = new Date(endYear-1900,endMonth-1,endDay,endHour,endMin,s);
            Activity pendingActivity = new Activity();
            pendingActivity.setActivityName(activityName);
            pendingActivity.setStartTime(startTime);
            pendingActivity.setEndTime(endTime);
            pendingActivity.setPlace(place);
            pendingActivity.setDescription(description);
            ActivityApplication application = new ActivityApplication(0, pendingActivity);
            application.setApplicant((ClubAdministrator) session.getAttribute("clubAdministrator"));

            activityApplicationRepository.save(application);
            session.setAttribute("deleted", true);
        } catch (Exception e) {
            session.setAttribute("deleted", false);
        }
        return "redirect:/clubAdministrator/activityApplication";
    }

    /**
     * 删除一个活动
     *
     * @param id 活动的ID
     * @param session 会话对象
     * @return 活动列表页面
     */
    @RequestMapping(value = "/activities/delete",method = POST)
    public String deleteActivity(@RequestParam("id") int id, HttpSession session) {
        try{
            session.setAttribute("deleted",activityRepository.deleteActivity(id));
        }catch (Exception e){
            session.setAttribute("deleted", false);
        }
        return "redirect:/clubAdministrator/activities";
    }
    
    /**
     * 查看社团活动列表
     *
     * @param keyword 搜索关键词
     * @param page 当前页码
     * @param session 会话对象
     * @param model model对象
     * @return 活动列表页面
     */
    @RequestMapping(value = "/activities", method = RequestMethod.GET)
    public String showActivities(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                                 @RequestParam(value = "page", defaultValue = "1") int page,
                                 HttpSession session, Model model) {
        Club club = (Club) session.getAttribute("club");
        List<Activity> allActivities = activityRepository.findActivitiesByClub(club);
        List<Activity> activityList;
        if (keyword == null || keyword.isEmpty()) {
            activityList = allActivities;
        } else {
            activityList = allActivities.stream()
                    .filter(activity -> activity.getActivityName() != null && activity.getActivityName().contains(keyword))
                    .collect(Collectors.toList());
        }
        model.addAttribute("activityList", activityList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (activityList.size() + 9) / 10);
        return "/clubAdministrator/activities";
    }


    /**
     * 查看公告列表
     *
     * @param keyword 搜索关键词
     * @param page 当前页码
     * @param session 会话对象
     * @param model model对象
     * @return 公告列表页面
     */
    @RequestMapping(value = "/announcements", method = GET)
    public String showAnnouncements(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                                    @RequestParam(value = "page", defaultValue = "1") int page,
                                    HttpSession session, Model model) {
        Club club = (Club) session.getAttribute("club");
        List<Announcement> allAnnouncements = announcementRepository.findAnnouncementsByClub(club);
        List<Announcement> announcementList;
        if (keyword == null || keyword.isEmpty()) {
            announcementList = allAnnouncements;
        } else {
            announcementList = allAnnouncements.stream()
                    .filter(announcement -> announcement != null && announcement.getPublisher() != null && announcement.getPublisher().getNickname().contains(keyword))
                    .collect(Collectors.toList());
        }
        model.addAttribute("announcementList", announcementList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (announcementList.size() + 9) / 10);
        return "/clubAdministrator/announcements";
    }


    /**
     * 删除公告
     *
     * @param id 公告ID
     * @param session 会话对象
     * @return 公告列表页面
     */
    @RequestMapping(value = "/announcements/delete", method = POST)
    public String deleteAnnouncement(@RequestParam("id") int id, HttpSession session) {
        try{
            Announcement announcement = announcementRepository.findOne(id);
            if (announcement != null) {
                session.setAttribute("deleted",announcementRepository.deleteAnnouncement(id));
            }
        }catch (Exception e){
            session.setAttribute("deleted", false);
        }
        return "redirect:/clubAdministrator/announcements";
    }


    /**
     * 发布公告页面
     *
     * @return 发布公告页面
     */
    @RequestMapping(value = "/publishAnnouncement", method = GET)
    public String showPublishAnnouncementPage() {

        return "/clubAdministrator/publishAnnouncement";
    }


    /**
     * 发布公告
     *
     * @param content 公告的内容
     * @param session 会话对象
     * @return 公告列表页面
     */
    @RequestMapping(value = "/publishAnnouncement", method = POST)
    public String publishAnnouncement(@RequestParam("content") String content,
                                      HttpSession session) {
        try {
            if (content.isEmpty()){
                throw new Exception();
            }
            Announcement announcement = new Announcement();
            announcement.setContent(content);
            ClubAdministrator clubAdministrator = (ClubAdministrator) session.getAttribute("clubAdministrator");
            announcement.setPublisher(clubAdministrator);
            announcementRepository.save(announcement);
            session.setAttribute("deleted", true);
        } catch (Exception e) {
            session.setAttribute("deleted", false);
        }
        return "redirect:/clubAdministrator/publishAnnouncement";
    }
	
	/**
	 * 查看社团管理员所在的社团信息
     *
     * @param session 会话对象
	 * @param model Model对象
	 * @return 社团信息页面
	 */
	@RequestMapping(value = "/clubInfo", method = GET)
    public String showClubInfo(HttpSession session, Model model) {
        Club club = (Club) session.getAttribute("club");
        model.addAttribute("club", club);
        return "/clubAdministrator/clubInfo";
    }

	
	/**
	 * 更新社团信息
     *
	 * @param college 新的学院名称
	 * @param description 新的社团描述
     * @param session 会话对象
	 * @return 社团信息页面
	 */
    @RequestMapping(value = "/clubInfo", method = RequestMethod.POST)
    public String updateClubInfo(@RequestParam("college") String college,
                                 @RequestParam("description") String description,
                                 HttpSession session) {
        try {
            if (college.isEmpty()||description.isEmpty()){
                throw new Exception();
            }
            Club club = (Club) session.getAttribute("club");
            if (club != null) {
                club.setCollege(college);
                club.setDescription(description);
                clubRepository.updateClub(club.getClubID(),club.getClubName(),
                        club.getCollege(),club.getDescription(),
                        club.getCreateTime());
            }
            session.setAttribute("deleted", true);
        } catch (Exception e) {
            session.setAttribute("deleted", false);
        }
        return "redirect:/clubAdministrator/clubInfo";
    }


    /**
     * 入团申请审批
     *
     * @param keyword 搜索关键词
     * @param page 当前页码
     * @param session 会话对象
     * @param model model对象
     * @return 入团申请审批页面
     */
    @RequestMapping(value = "/membershipApplications", method = GET)
    public String showMembershipApplications(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                                             @RequestParam(value = "page", defaultValue = "1") int page,
                                             HttpSession session, Model model) {
        Club club = (Club) session.getAttribute("club");
        List<MembershipApplication> allApplications = membershipApplicationRepository.findAllByClub(club);
        List<MembershipApplication> applicationList;
        if (keyword == null || keyword.isEmpty()) {
            applicationList = allApplications;
        } else {
            applicationList = allApplications.stream()
                    .filter(application -> application.getApplicant() != null && application.getApplicant().getUsername().contains(keyword))
                    .collect(Collectors.toList());
        }
        model.addAttribute("membershipApplicationList", applicationList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (applicationList.size() + 9) / 10);
        return "/clubAdministrator/membershipApplications";
    }


    /**
     * 审批通过入团申请
     *
     * @param id 申请ID
     * @return 入团申请页面
     */
    @RequestMapping(value = "/membershipApplications/pass", method = POST)
    public String passMembershipApplication(@RequestParam("id") int id) {
        MembershipApplication application = membershipApplicationRepository.findOne(id);
        if (application != null) {
            application.setStatus(1);
            membershipApplicationRepository.updateMembershipApplication(application);

        }
        return "redirect:/clubAdministrator/membershipApplications";
    }

    /**
     * 审批拒绝入团申请
     *
     * @param id 申请ID
     * @return 入团申请页面
     */
    @RequestMapping(value = "/membershipApplications/rejected", method = POST)
    public String rejectMembershipApplication(@RequestParam("id") int id) {
        MembershipApplication application = membershipApplicationRepository.findOne(id);
        if (application != null) {
            application.setStatus(-1);
            membershipApplicationRepository.updateMembershipApplication(application);
        }
        return "redirect:/clubAdministrator/membershipApplications";
    }

    /**
     * 退出登录
     *
     * @param session 会话对象
     * @return 系统首页
     */
    @RequestMapping(value = "/logout", method = GET)
    public String logout(HttpSession session) {
        session.removeAttribute("clubAdministrator");
        session.removeAttribute("club");
        session.invalidate();
        return "redirect:/";
    }

}